package manet.comm;

import java.util.ArrayList;
import java.util.LinkedList;


/**
 * @author grin0077
 *
 */
public class DefaultCommunicator implements Communicator {
	
	private static final String BROADCASTADDR = "ALL";
	
	private ArrayList<DefaultCommunicator> endpoints = null;
	private String address = null;
	private LinkedList<String> msgQueue = null;
	private boolean listening = false;

	
	public DefaultCommunicator(String addr) {
		this.endpoints = new ArrayList<DefaultCommunicator>();
		this.address = addr;
		this.msgQueue = new LinkedList<String>();
		this.listening = true;
	}

	/** Add an available endpoint */
	public void addEndpoint(DefaultCommunicator comm) {
		if (!this.endpoints.contains(comm)) this.endpoints.add(comm);
	}
	
	/** Remove an available endpoint */
	public void removeEndpoint(DefaultCommunicator comm) {
		if (this.endpoints.remove(comm));
	}
	
	/** Get address of current instance */
	public String getAddress() {
		return this.address;
	}
	
	/* (non-Javadoc)
	 * @see manet.comm.Communicator#getListeningState()
	 */
	public boolean getListeningState() {
		return this.listening;
	}

	/* (non-Javadoc)
	 * @see manet.comm.Communicator#getQueuedMessage()
	 */
	public String getQueuedMessage() {
		if(this.newMessagesAvailable()) return this.msgQueue.removeFirst();
		else return null;
	}

	/* (non-Javadoc)
	 * @see manet.comm.Communicator#newMessagesAvailable()
	 */
	public boolean newMessagesAvailable() {
		return !this.msgQueue.isEmpty();
	}

	/** Receive a direct message if listening */
	public void receiveMessage(String message) {
		if(this.listening && message != null) this.msgQueue.addLast(message);
		System.out.println(this.address + " received message: " + message);
	}
	
	/* (non-Javadoc)
	 * @see manet.comm.Communicator#sendMessage(java.lang.String)
	 */
	public void sendMessage(String message) {
		sendMessage(message, DefaultCommunicator.BROADCASTADDR);
	}

	/* (non-Javadoc)
	 * @see manet.comm.Communicator#sendMessage(java.lang.String, java.lang.String)
	 */
	public void sendMessage(String message, String entityName) {
		System.out.println(this.address + " sending message: " + message + " to: " + entityName);
		for(DefaultCommunicator comm:this.endpoints) {
			if("ALL".equals(entityName) || comm.getAddress().equals(entityName)) {
				comm.receiveMessage(message);
			}
		}
	}

	/* (non-Javadoc)
	 * @see manet.comm.Communicator#setListeningState(boolean)
	 */
	public void setListeningState(boolean listening) {
		this.listening = listening;

	}

	/* (non-Javadoc)
	 * @see manet.comm.Communicator#isListening()
	 */
	@Override
	public boolean isListening() {
		// TODO Auto-generated method stub
		return false;
	}

}
